package walletuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"github.com/shopspring/decimal"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserCancelWithdrawLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserCancelWithdrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserCancelWithdrawLogic {
	return &UserCancelWithdrawLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 取消提现
func (l *UserCancelWithdrawLogic) UserCancelWithdraw(in *pb.UserCancelWithdrawReq) (*pb.UserCancelWithdrawResp, error) {
	defer utils.RecoverPanic()

	var wf *wallet.UserWithdrawFlow
	var err error
	wf, err = l.svcCtx.UserWithdrawFlowModel.FindOne(l.ctx, in.FlowNo)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		if err != wallet.ErrNotFound {
			err = xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		} else {
			err = xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "not found")
		}
		return nil, err
	}

	if wf.State != walletkey.WithdrawFlowStateNotAudit {
		l.Logger.Errorf("err == ", zap.Error(xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "state error")))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "state error")
	}

	// 查询用户钱包
	var uw *wallet.UserWallet
	uw, err = l.svcCtx.UserWalletModel.FindOneByUidMoneyType(l.ctx, in.Uid, wf.MoneyType)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	// 更新用户钱包和流水
	err = l.svcCtx.UserWalletModel.Trans(l.ctx, func(ctx context.Context, tx sqlx.Session) error {
		// 更新提现流水
		err2 := l.svcCtx.UserWithdrawFlowModel.UpdateStateTrans(ctx, tx, wf.FlowNo, walletkey.WithdrawFlowStateCancel, 0)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		// 更新用户钱包
		err2 = l.svcCtx.UserWalletModel.AddAmountTrans(ctx, tx, wf.MoneyAmount, uw.Id, in.Uid, wf.MoneyType)
		if err2 != nil {
			l.Logger.Errorf("err == ", zap.Error(err2))
			return xerr.NewGrpcErrCodeMsg(xerr.DbError, err2.Error())
		}
		return nil
	})
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	var rsp pb.UserCancelWithdrawResp
	var dUwBalance = decimal.NewFromInt(uw.Amount)
	var dOrderFlowAmount = decimal.NewFromInt(wf.MoneyAmount)

	rsp.Balance = dUwBalance.Add(dOrderFlowAmount).Div(decimal.NewFromInt(walletkey.MoneyScale)).StringFixedBank(2)
	rsp.MoneyType = uw.MoneyType
	return &rsp, nil
}
